package edu.uit.se.laps.web.controller;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import edu.uit.se.laps.web.model.DonHang;
import edu.uit.se.laps.web.model.SanPham;
import edu.uit.se.laps.web.util.HibernateUtil;

public class DonHangManager extends HibernateUtil{
	
	public DonHang addDonHang(DonHang donHang){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(donHang);
		session.getTransaction().commit();
		return donHang;
	}
	
	public DonHang deleteDonHang(int id){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		//DonHang donHang = (DonHang) session.load(DonHang.class, id);
		DonHang donHang = (DonHang) session.get(DonHang.class, id);
		if (null != donHang) {
			session.delete(donHang);
		}
		session.getTransaction().commit();
		return donHang;
	}
	
	public List<DonHang> list(){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<DonHang> donHangs = null;
		try {
			donHangs = (List<DonHang>)session.createQuery("from DonHang").list();
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return donHangs;
	}
	
	public List<DonHang> getDHUserList(int idUser){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<DonHang> donHangs = null;
		try {
			//donHangs = (List<DonHang>)session.createQuery("from DonHang").list();
			
			String sql = "from DonHang where idUser = ?";
			Query query = session.createQuery(sql);
			query.setInteger(0, idUser);
			
			donHangs = (List<DonHang>)query.list();
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return donHangs;
	}
	
	public DonHang getDH_ID(int id){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		
		DonHang donHang = (DonHang) session.get(DonHang.class, id);
		
		session.getTransaction().commit();
		return donHang;
	}
	
	public boolean updateDonHang(DonHang donHang){
		boolean result = false;
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		try {
			session.update(donHang);
			result = true;
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return result;
	}
}
